package 数组.二分查找.搜索插入位置;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/11 9:29
 * @description:给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {1,2,3,5,6,7};
        int target = 3;
        System.out.println(search(arr, target));
    }

    public static int search(int[] arr,int target){
        //采用二分法
        int left = 0;
        int right = arr.length - 1;
        int mid = 0;
        while (left <= right){
            mid = left + (right - left) / 2;
            if (arr[mid] == target){
                return mid;
            }else if (arr[mid] < target){
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return mid;
    }
}
